// UserAdapter.java
package com.tzkyzj.tiremanagersystem.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.tzkyzj.tiremanagersystem.R;
import java.util.List;
import java.util.Map;

public class UserAdapter extends RecyclerView.Adapter<UserAdapter.UserViewHolder> {

    private List<Map<String, Object>> userList;
    private OnUserActionListener listener;

    public interface OnUserActionListener {
        void onUserStatusChanged(Long userId, boolean enabled);
        void onEditUser(Long userId, Map<String, Object> user);
        void onDeleteUser(Long userId, String username);
    }

    public UserAdapter(List<Map<String, Object>> userList, OnUserActionListener listener) {
        this.userList = userList;
        this.listener = listener;
    }

    @NonNull
    @Override
    public UserViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_user, parent, false);
        return new UserViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull UserViewHolder holder, int position) {
        Map<String, Object> user = userList.get(position);
        holder.bind(user, listener);
    }

    @Override
    public int getItemCount() {
        return userList.size();
    }

    public void updateData(List<Map<String, Object>> newUserList) {
        this.userList = newUserList;
        notifyDataSetChanged();
    }

    static class UserViewHolder extends RecyclerView.ViewHolder {
        private TextView tvUsername, tvRole, tvStatus, tvCompany, tvVehiclePlate;
        private Switch switchEnabled;
        private ImageButton btnEdit, btnDelete;

        public UserViewHolder(@NonNull View itemView) {
            super(itemView);

            tvUsername = itemView.findViewById(R.id.tv_username);
            tvRole = itemView.findViewById(R.id.tv_role);
            tvStatus = itemView.findViewById(R.id.tv_status);
            tvCompany = itemView.findViewById(R.id.tv_company);
            tvVehiclePlate = itemView.findViewById(R.id.tv_vehicle_plate);
            switchEnabled = itemView.findViewById(R.id.switch_enabled);
            btnEdit = itemView.findViewById(R.id.btn_edit);
            btnDelete = itemView.findViewById(R.id.btn_delete);
        }

        public void bind(Map<String, Object> user, OnUserActionListener listener) {
            // 绑定用户数据
            bindUserData(user);

            // 设置点击监听器
            setClickListeners(user, listener);
        }

        private void bindUserData(Map<String, Object> user) {
            // 用户名
            String username = (String) user.get("username");
            tvUsername.setText(username != null ? username : "未知用户");

            // 角色
            String role = getRoleDisplayName(user.get("role"));
            tvRole.setText(role);
            setRoleBadgeColor(tvRole, role);

            // 状态
            Boolean enabled = getBooleanValue(user.get("enabled"));
            String statusText = enabled != null && enabled ? "启用" : "禁用";
            tvStatus.setText(statusText);
            setStatusBadgeColor(tvStatus, enabled);

            // 状态开关
            switchEnabled.setChecked(enabled != null && enabled);

            // 运输公司
            String company = (String) user.get("transportCompany");
            tvCompany.setText(company != null ? "公司: " + company : "公司: 未设置");

            // 车牌号
            String vehiclePlate = (String) user.get("vehiclePlateNumber");
            tvVehiclePlate.setText(vehiclePlate != null ? "车牌: " + vehiclePlate : "车牌: 未设置");
        }

        private void setClickListeners(Map<String, Object> user, OnUserActionListener listener) {
            Long userId = getLongValue(user.get("id"));

            // 状态开关监听
            switchEnabled.setOnCheckedChangeListener(null); // 先清除之前的监听器
            switchEnabled.setOnCheckedChangeListener((buttonView, isChecked) -> {
                if (listener != null && userId != null) {
                    listener.onUserStatusChanged(userId, isChecked);
                }
            });

            // 编辑按钮监听
            btnEdit.setOnClickListener(v -> {
                if (listener != null && userId != null) {
                    listener.onEditUser(userId, user);
                }
            });

            // 删除按钮监听
            btnDelete.setOnClickListener(v -> {
                if (listener != null && userId != null) {
                    String username = (String) user.get("username");
                    listener.onDeleteUser(userId, username != null ? username : "该用户");
                }
            });
        }

        private String getRoleDisplayName(Object roleObj) {
            if (roleObj == null) return "未知角色";

            String role;
            if (roleObj instanceof Map) {
                // 如果是Map类型，获取name字段
                role = (String) ((Map) roleObj).get("name");
            } else {
                role = roleObj.toString();
            }

            switch (role) {
                case "ADMIN": return "管理员";
                case "COMPANY": return "运输公司";
                case "DRIVER": return "司机";
                default: return role;
            }
        }

        private void setRoleBadgeColor(TextView textView, String role) {
            switch (role) {
                case "管理员":
                    textView.setBackgroundResource(R.drawable.role_badge_admin);
                    break;
                case "运输公司":
                    textView.setBackgroundResource(R.drawable.role_badge_company);
                    break;
                case "司机":
                    textView.setBackgroundResource(R.drawable.role_badge_driver);
                    break;
                default:
                    textView.setBackgroundResource(R.drawable.role_badge_background);
            }
        }

        private void setStatusBadgeColor(TextView textView, Boolean enabled) {
            if (enabled != null && enabled) {
                textView.setBackgroundResource(R.drawable.status_badge_enabled);
            } else {
                textView.setBackgroundResource(R.drawable.status_badge_disabled);
            }
        }

        private Boolean getBooleanValue(Object value) {
            if (value instanceof Boolean) {
                return (Boolean) value;
            } else if (value instanceof String) {
                return Boolean.parseBoolean((String) value);
            }
            return null;
        }

        private Long getLongValue(Object value) {
            if (value instanceof Long) {
                return (Long) value;
            } else if (value instanceof Integer) {
                return ((Integer) value).longValue();
            } else if (value instanceof Double) {
                return ((Double) value).longValue();
            }
            return null;
        }
    }
}